package org.threebitsoftware.tbb.Contact_GUI;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;

import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.List;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.custom.CCombo;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.threebitsoftware.tbb.dao.Contact;
import org.threebitsoftware.tbb.engine.EngineUtil;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Control;

public class FileExport_GUI extends Dialog {
	private static Logger logger = Logger.getLogger(FileExport_GUI.class);
	
	private Text pathText_;
	private Shell shell;
	private Object result_;
	ListViewer listViewer ;
	ArrayList<Contact> testCont = new ArrayList<Contact>();
	private Contact clickedContactItem; 
	private List vcardListx;
	private Button btnBrowse;
	private Button btnCancel;
	private Button btnExport;
	
	/**
	 * Create the shell.
	 * 
	 * @param display
	 */
	public FileExport_GUI(Shell parent, int style, ArrayList<Contact> contactCollection) {
		super(parent, style);
		setText("SWT Dialog");
		testCont = contactCollection;
	}
	
	public FileExport_GUI (Shell parent, int style){
		super(parent, style);
	}

	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		
		Display display = getParent().getDisplay();
//		FileImport_GUI shell = new FileImport_GUI(display);

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result_;
	}

	/**
	 * Create the shell.
	 * 
	 * @param display
	 * Create contents of the shell.
	 */

	protected void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM
				| SWT.APPLICATION_MODAL);
		shell.setBackground(SWTResourceManager
				.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		shell.setSize(471, 250);
		shell.setText("TBB File Export");

		
		/**
		 * handle the list of contacts
		 */
		{
			listViewer = new ListViewer(shell, SWT.BORDER);
			vcardListx = listViewer.getList();
		
			populateList(vcardListx, testCont);
			
			vcardListx.setBounds(0, 20, 465, 146);
			
			vcardListx.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					System.out.println("List created");
					List getSelectContactInfo = (List) e.getSource();

//					System.out.println("Selected List Item is: " + getSelectContactInfo.getText());
					int selected = getSelectContactInfo.getSelectionIndex();
					ArrayList<List> obj = (ArrayList<List>) getSelectContactInfo.getData();
					List selectedContactListItem = obj.get(selected);
//					emailAddressvectorList_.add((EmailAddress) selectedEmailCombo.getData());
					clickedContactItem = (Contact) selectedContactListItem.getData();
				}
			});

		/**
		 * the label contact(s)
		 */
		{
			Label lblFileExport = new Label(shell, SWT.NONE);
			lblFileExport.setBounds(0, 0, 106, 39);
			lblFileExport.setText("Contact(s)");
		}
		
		/**
		 * handle the path text box
		 */
		{
			pathText_ = new Text(shell, SWT.BORDER);
			pathText_.setBounds(64, 172, 321, 19);
		}
		
		/**
		 * handle the export button
		 */
		{
			btnExport = new Button(shell, SWT.NONE);
			btnExport.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					FileExport_GUI fg = new FileExport_GUI(shell, 0);
					System.out.println("Exporting " + clickedContactItem.toString());			
					Contact [] contactToBeStoreArray = new Contact[] {clickedContactItem};
					
					try {
						System.out.println("Exporting to " + pathText_.getText());
						String fileExtenson = pathText_.getText();
						
						if(fileExtenson.substring(fileExtenson.indexOf(".")).equalsIgnoreCase(".txt")) {
							
							System.out.println("the simple text import should be called here");
							EngineUtil.useFileExportHandler("org.threebitsoftware.tbb.module.simpletext.SimpleTextExporter", pathText_.getText(), contactToBeStoreArray);
							logger.info("Export finished for " + contactToBeStoreArray[0] + " Check " + pathText_.getText());
							System.out.println("Export finished. Check " + pathText_.getText());
							JOptionPane.showMessageDialog(null,"Simple Text Export finished. Check " + pathText_.getText(),
									null, 
									JOptionPane.NO_OPTION);
							
						} else {
							
							EngineUtil.useFileExportHandler("org.threebitsoftware.tbb.module.vcard.VCardExporter", pathText_.getText(), contactToBeStoreArray);
							logger.info("Imported finished for " + contactToBeStoreArray[0] + " Check " + pathText_.getText());
							JOptionPane.showMessageDialog(null,"VCard Export finished. Check " + pathText_.getText(),
									null, 
									JOptionPane.NO_OPTION);
						}
						
					} catch (ClassNotFoundException classnotfound) {
						System.out.println("Did not export.");
						classnotfound.printStackTrace();
					}
					
				}
			});
			btnExport.setBounds(217, 197, 68, 23);
			btnExport.setText("E&xport");
		}
		
		/**
		 * handle the path label 
		 */
		{	Label lblPath = new Label(shell, SWT.NONE);
			lblPath.setBounds(20, 175, 48, 19);
			lblPath.setText("Path");
		}
		
		/**
		 * handle the cancel button
		 */
		{
			btnCancel = new Button(shell, SWT.NONE);
			btnCancel.addMouseListener(new MouseAdapter() {
				/**
				 * on mouse click of cancel button close this gui
				 */
				@Override
				public void mouseDown(MouseEvent e) {
					shell.close();
				}
			});
			btnCancel.setBounds(132, 197, 68, 23);
			btnCancel.setText("&Cancel");
		}

		/**
		 * handle the browse button
		 */
		{
			btnBrowse = new Button(shell, SWT.NONE);
			btnBrowse.addMouseListener(new MouseAdapter() {
				
				/**
				 * Open file browser when the browse button is pressed
				 */
				@Override
				public void mouseDown(MouseEvent e) {
					FileDialog saveDialog = new FileDialog(new Shell(), SWT.SAVE);
					saveDialog.setFilterExtensions(new String []{"*.vcf","*.txt"});
					saveDialog.open();
					pathText_.setText(saveDialog.getFilterPath() != "" ? 
							saveDialog.getFilterPath()+ "\\" + 
							saveDialog.getFileName() : "");
				}
			});
			btnBrowse.setBounds(391, 172, 68, 23);
			btnBrowse.setText("&Browse");
		}
		shell.setTabList(new Control[]{vcardListx, pathText_, btnBrowse, btnCancel, btnExport});
	}
	}
	/**
	 * 
	 * @param listObject
	 * @param listItems
	 * @return
	 */
	public List populateList(List listObject, ArrayList<Contact> listItems) {
		
		Enumeration enumerateListItems = Collections.enumeration(listItems);
		ArrayList<List> listArrayListData = new ArrayList<List>();
		
		while (enumerateListItems.hasMoreElements()) {
			List currentListItem = new List(shell, 0);
			Contact currentContact = (Contact) enumerateListItems.nextElement();
			currentListItem.setData(currentContact);
			
			listObject.add(currentContact.getFirstName() + " " + currentContact.getLastName());
			listArrayListData.add(currentListItem);
		}
		
		listObject.setData(listArrayListData);
		return listObject;	
	}
}
